package com.forezp.configclient.rabbitMq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version V1.0  </br>
 * @ClassName NewTask </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 11/23/2018 10:34 AM</br>
 */
public class NewTask {
    //队列名称
    private final static String QUEUE_NAME = "workqueue";
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接和频道
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("root");
        factory.setPassword("root");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //两件事来确保信息不会被丢失：我们需要给所有的队列和消息设置持久化的标志
        //1.设置队列持久化
        boolean durable = true;
        //声明队列
        //注：RabbitMQ不允许使用不同的参数重新定义一个队列，所以已经存在的队列，我们无法修改其属性。
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
        //发送10条消息，依次在消息后面附加1-10个点
        for (int i = 0; i < 10; i++)
        {
            String dots = "";
            for (int j = 0; j <= i; j++)
            {
                dots += ".";
            }
            String message = "helloworld" + dots+dots.length();
            //2.设置消息持久化,通过设置MessageProperties（implements BasicProperties）值为PERSISTENT_TEXT_PLAIN。
            channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
            System.out.println(" [x] Sent '" + message + "'");
        }
        //关闭频道和资源
        channel.close();
        connection.close();

    }
}
